#!/usr/bin/env python
#
# Copyright (C) 2011 Clement Lorteau <clem@lorteau.fr>	
#		
# This file is part of QuickScreenShots.		
# 	
# This program is free software; you can redistribute it and/or modify	
# it under the terms of the GNU General Public License as published by		
# the Free Software Foundation; version 3.	
# 	
# This program is distributed in the hope that it will be useful,		
# but WITHOUT ANY WARRANTY; without even the implied warranty of		
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the		
# GNU General Public License for more details.		
# 		
# You should have received a copy of the GNU General Public License		
# along with this program; if not, write to the Free Software		
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

import wx
from wx.lib.buttons import ThemedGenBitmapTextButton as bbutton
from wx.lib.filebrowsebutton import DirBrowseButton
import wx.lib.intctrl as IC
import options
from options import Options
from __init__ import resources

class OptionsDialog(wx.Dialog):
    def __init__(self, options, *args, **kwds):
        self.keyspressed = []
        self.keyMap = {}
        self.gen_keymap()
        kwds["style"] = wx.DEFAULT_DIALOG_STYLE
        wx.Dialog.__init__(self, *args, **kwds)

        okbmp = wx.Bitmap("%s/ok_16.png" % resources, wx.BITMAP_TYPE_PNG)
        cancelbmp = wx.Bitmap("%s/cancel_16.png" % resources, wx.BITMAP_TYPE_PNG)
        generalbmp = wx.Bitmap("%s/settings_32.png" % resources, wx.BITMAP_TYPE_PNG)
        savebmp = wx.Bitmap("%s/save_32.png" % resources, wx.BITMAP_TYPE_PNG)
        rotatebmp = wx.Bitmap("%s/rotate_32.png" % resources, wx.BITMAP_TYPE_PNG)
        shadowbmp = wx.Bitmap("%s/shadow_32.png" % resources, wx.BITMAP_TYPE_PNG)
        
#		font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
#       smallfont = wx.Font(font.GetPointSize()-5, font.GetFamily(), font.GetStyle(),
#              	            font.GetWeight(), font.GetUnderlined(), font.GetFaceName(),
#                 	        font.GetEncoding())
#       self.SetFont(smallfont)
                
        self.okButton = bbutton(self, wx.ID_OK, okbmp, '  OK')
        self.cancelButton = bbutton(self, wx.ID_CANCEL, cancelbmp, '  Cancel')
        
        imglist = wx.ImageList(32, 32)
        imglist.Add(generalbmp)
        imglist.Add(savebmp)
        imglist.Add(shadowbmp)
        imglist.Add(rotatebmp)
        self.book = wx.Listbook(self, -1, style=wx.BK_LEFT)
        self.book.AssignImageList(imglist)
        
        self.generalpanel = wx.Panel(self.book)
        self.savepanel = wx.Panel(self.book)
        self.shadowpanel = wx.Panel(self.book)
        self.rotatepanel = wx.Panel(self.book)
        
        #general page
        self.delaySpin = wx.SpinCtrl(self.generalpanel, max=360)
        self.label_1 = wx.StaticText(self.generalpanel, -1,
                                     'Screenshot delay in seconds:')
        self.label_2 = wx.StaticText(self.generalpanel, -1,
                                     'Full desktop screenshot keyboard shortcut:')
        self.label_3 = wx.StaticText(self.generalpanel, -1,
                                     'Active window screenshot keyboard shortcut:')                             
        self.label_4 = wx.StaticText(self.generalpanel, -1,
                                     'Region screenshot keyboard shortcut:')
        self.desktopTxt = wx.TextCtrl(self.generalpanel)
        self.windowTxt = wx.TextCtrl(self.generalpanel)
        self.regionTxt = wx.TextCtrl(self.generalpanel)
        self.updatescheckbox = wx.CheckBox(self.generalpanel, -1, "Check for updates on startup once a week")
        self.autostartcheckbox = wx.CheckBox(self.generalpanel, -1, "Auto start with windows")
        self.startminicheckbox = wx.CheckBox(self.generalpanel, -1, "Start minimized")
        self.copycheckbox = wx.CheckBox(self.generalpanel, -1, "Auto copy to clipboard")
        self.cursorcheckbox = wx.CheckBox(self.generalpanel, -1, "Include mouse cursor in screenshots")
        self.soundcheckbox = wx.CheckBox(self.generalpanel, -1, "Play sound on screenshot")
        
        #auto save page
        self.saveCheck = wx.CheckBox(self.savepanel, label='Auto save screenshots')
        self.label_5 = wx.StaticText(self.savepanel, -1,
                                     'Directory where screenshots will be saved:')
        self.label_6 = wx.StaticText(self.savepanel, -1,
                                     'Base file name of auto saved screenshots:')
        self.folderTxt = DirBrowseButton(self.savepanel, labelText='', buttonText='Browse...')
        self.nameTxt = wx.TextCtrl(self.savepanel)
        
        #shadow page
        self.label_7 = wx.StaticText(self.shadowpanel, -1,
                                     'Background color:')
        self.label_8 = wx.StaticText(self.shadowpanel, -1,
                                     'Shadow color:')
        self.background_color_ctrl = wx.ColourPickerCtrl(self.shadowpanel,
                                                         style=wx.CLRP_SHOW_LABEL)
        self.shadow_color_ctrl = wx.ColourPickerCtrl(self.shadowpanel,
                                                     style=wx.CLRP_SHOW_LABEL)
                                                     
        #rotate page
        self.label_9 = wx.StaticText(self.rotatepanel, -1,
                                     'Angle of rotation:')
        self.label_10 = wx.StaticText(self.rotatepanel, -1,
                                      'Background color:')
        #self.rot_angle_ctrl = KC.KnobCtrl(self.rotatepanel)
        self.rotbg_color_ctrl = wx.ColourPickerCtrl(self.rotatepanel,
                                                    style=wx.CLRP_SHOW_LABEL)
        self.rot_angle_txt = IC.IntCtrl(self.rotatepanel, min=-360, max=360,
                                        style=wx.TE_CENTRE)
        
        #self.Bind(KC.EVT_KC_ANGLE_CHANGED, self.OnAngleChanged)
        self.Bind(IC.EVT_INT, self.OnIntChanged)
        self.desktopTxt.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.desktopTxt)
        self.windowTxt.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.windowTxt)
        self.regionTxt.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.regionTxt)
        
        self.__set_properties()
        self.__do_layout()
        
        self.SetOptions(options)

    def __set_properties(self):
        self.SetTitle("Settings")
        self.SetIcon(wx.Icon("%s/settings_16.png" % resources, wx.BITMAP_TYPE_PNG))
        #self.rot_angle_ctrl.Show(False) #i can't figure the parameters
        #self.rot_angle_ctrl.SetAngularRange(90, 450)
        #self.rot_angle_ctrl.SetTags(range(0, 450, 90))
        #self.rot_angle_ctrl.SetValue(0)
        #self.rot_angle_ctrl.SetBoundingColour(wx.Colour(170, 170, 150))

    def __do_layout(self):
        self.book.SetSizeHints(-1, 8*36)
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        
        grid_sizer_1 = wx.GridSizer(1, 2, 0, 5)
        grid_sizer_1.Add(self.okButton, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_CENTER_HORIZONTAL)
        grid_sizer_1.Add(self.cancelButton, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_CENTER_HORIZONTAL)
        
        grid_sizer_2 = wx.GridSizer(5, 1, 0, 3)
        grid_sizer_2.Add(self.autostartcheckbox, 0, wx.ALL, 5)
        grid_sizer_2.Add(self.startminicheckbox, 0, wx.ALL, 5)
        grid_sizer_2.Add(self.updatescheckbox, 0, wx.ALL, 5)
        grid_sizer_2.Add(self.copycheckbox, 0, wx.ALL, 5)
        grid_sizer_2.Add(self.cursorcheckbox, 0, wx.ALL, 5)
        grid_sizer_2.Add(self.soundcheckbox, 0, wx.ALL, 5)
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_2.Add(self.label_1, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 1)
        sizer_2.Add(self.delaySpin, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 1)
        grid_sizer_2.Add(sizer_2, 0, wx.ALL, 5)
        grid_sizer_2.Add(self.label_2, 1, wx.ALL, 5)
        grid_sizer_2.Add(self.desktopTxt, 1, wx.ALL, 5)
        grid_sizer_2.Add(self.label_3, 1, wx.ALL|wx.ALIGN_BOTTOM, 5)
        grid_sizer_2.Add(self.windowTxt, 1, wx.ALL, 5)
        grid_sizer_2.Add(self.label_4, 1, wx.ALL|wx.ALIGN_BOTTOM, 5)
        grid_sizer_2.Add(self.regionTxt, 1, wx.ALL, 5)
        self.generalpanel.SetSizer(grid_sizer_2)
        
        grid_sizer_3 = wx.GridSizer(4, 1, 0, 5)
        grid_sizer_3.Add(self.saveCheck, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
        grid_sizer_3.Add(self.label_5, 1, wx.ALL|wx.ALIGN_BOTTOM, 5)
        grid_sizer_3.Add(self.folderTxt, 0, wx.ALL, 0)
        grid_sizer_3.Add(self.label_6, 1, wx.ALL|wx.ALIGN_BOTTOM, 5)
        grid_sizer_3.Add(self.nameTxt, 0, wx.ALL, 8)
        self.savepanel.SetSizer(grid_sizer_3)
        
        grid_sizer_4 = wx.GridSizer(2, 2, 30, 5)
        grid_sizer_4.Add(self.label_7, 1, wx.ALL|wx.ALIGN_BOTTOM, 5)
        grid_sizer_4.Add(self.background_color_ctrl, 0, wx.ALL|wx.ALIGN_BOTTOM, 0)
        grid_sizer_4.Add(self.label_8, 1, wx.ALL, 5)
        grid_sizer_4.Add(self.shadow_color_ctrl, 0, wx.ALL, 0)
        self.shadowpanel.SetSizer(grid_sizer_4)
        
        grid_sizer_5 = wx.GridSizer(2, 2, 30, 5)
        grid_sizer_5.Add(self.label_9, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
        # sizer_4 = wx.BoxSizer(wx.VERTICAL)
        # sizer_4.Add(self.rot_angle_ctrl, 1, wx.EXPAND|wx.ALL, 5)
        # sizer_4.Add(self.rot_angle_txt, 0, wx.ALIGN_CENTER, 0)
        # grid_sizer_5.Add(sizer_4, 1, wx.ALL|wx.EXPAND, 0)
        grid_sizer_5.Add(self.rot_angle_txt, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
        grid_sizer_5.Add(self.label_10, 1, wx.ALL, 5)
        grid_sizer_5.Add(self.rotbg_color_ctrl, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 0)
        self.rotatepanel.SetSizer(grid_sizer_5)
        
        self.book.AddPage(self.generalpanel, 'General', imageId=0)
        self.book.AddPage(self.savepanel, 'Auto save', imageId=1)
        self.book.AddPage(self.shadowpanel, 'Shadow', imageId=2)
        self.book.AddPage(self.rotatepanel, 'Rotate', imageId=3)
        sizer_1.Add(self.book, 1, wx.ALL|wx.EXPAND, 5)
        sizer_1.Add(grid_sizer_1, 0, wx.ALL|wx.EXPAND, 10)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        self.Layout()
        
    def OnKeyDown(self, event):
        if self.keyspressed.count(event.GetKeyCode()) == 0:
            c = self.GetKeyPress(event)
            event.GetEventObject().SetValue(c)

    def OnAngleChanged(self, event):
        value = event.GetValue()
        self.rot_angle_txt.SetLabel(str(value))
        
    def OnIntChanged(self, event):
        #self.rot_angle_ctrl.SetValue(event.GetValue())
        pass
        
    def OnButton(self, event):
        print "OnButton"
        return False
        
    def GetOptions(self):
        self.Apply()
        return self.options
        
    def Hex2WXColour(self, hex):
    	"""
    	convert hex color string, i.e. '#ff0000' into wx.Colour object
    	"""
    	hexr = hex[1]+hex[2]
    	hexg = hex[3]+hex[4]
    	hexb = hex[5]+hex[6]
    	c = wx.Colour(int(hexr, 16), int(hexg, 16), int(hexb, 16))
    	return c
        
    def SetOptions(self, options):
        self.options = options
        self.updatescheckbox.SetValue(options.check_updates.GetValue())
        self.autostartcheckbox.SetValue(options.win_start.GetValue())
        self.startminicheckbox.SetValue(options.start_minimized.GetValue())
        self.cursorcheckbox.SetValue(options.include_cursor.GetValue())
        self.copycheckbox.SetValue(options.copy_use.GetValue())
        self.soundcheckbox.SetValue(options.sound_use.GetValue())
        self.delaySpin.SetValue(options.delay.GetValue())
        self.saveCheck.SetValue(options.save_use.GetValue())
        self.folderTxt.SetValue(options.save_dir.GetValue())
        self.nameTxt.SetValue(options.save_file.GetValue())
        color = options.shadow_background.GetValue()
        self.background_color_ctrl.SetColour(self.Hex2WXColour(color))
        color = options.shadow_color.GetValue()
        self.shadow_color_ctrl.SetColour(self.Hex2WXColour(color))
        self.rot_angle_txt.SetValue(options.rotate_angle.GetValue())
        color = options.rotate_background.GetValue()
        self.rotbg_color_ctrl.SetColour(self.Hex2WXColour(color))
        self.desktopTxt.SetValue(options.kb_desktop.GetValue())
        self.windowTxt.SetValue(options.kb_window.GetValue())
        self.regionTxt.SetValue(options.kb_region.GetValue())
    
    def Apply(self):
        o = self.options
        o.win_start.SetValue(self.autostartcheckbox.GetValue())
        o.check_updates.SetValue(self.updatescheckbox.GetValue())
        o.start_minimized.SetValue(self.startminicheckbox.GetValue())
        o.include_cursor.SetValue(self.cursorcheckbox.IsChecked())
        o.copy_use.SetValue(self.copycheckbox.GetValue())
        o.sound_use.SetValue(self.soundcheckbox.GetValue())
        o.delay.SetValue(self.delaySpin.GetValue())
        o.save_use.SetValue(self.saveCheck.GetValue())
        o.save_dir.SetValue(self.folderTxt.GetValue())
        o.save_file.SetValue(self.nameTxt.GetValue())
        col = self.background_color_ctrl.GetColour().GetAsString(wx.C2S_HTML_SYNTAX)
        o.shadow_background.SetValue(col)
        col = self.shadow_color_ctrl.GetColour().GetAsString(wx.C2S_HTML_SYNTAX)
        o.shadow_color.SetValue(col)
        o.rotate_angle.SetValue(self.rot_angle_txt.GetValue())
        col = self.rotbg_color_ctrl.GetColour().GetAsString(wx.C2S_HTML_SYNTAX)
        o.rotate_background.SetValue(col)
        o.kb_desktop.SetValue(self.desktopTxt.GetValue())
        o.kb_window.SetValue(self.windowTxt.GetValue())
        o.kb_region.SetValue(self.regionTxt.GetValue())
        self.options = o
        save_dir = o.save_dir.GetValue()
        
        
    def gen_keymap(self):
        """source: Josiah carlson - http://come.to/josiah"""
        keys = ("BACK", "TAB", "RETURN", "ESCAPE", "SPACE", "DELETE", "START",
            "LBUTTON", "RBUTTON", "CANCEL", "MBUTTON", "CLEAR", "PAUSE",
            "CAPITAL", "PRIOR", "NEXT", "END", "HOME", "LEFT", "UP", "RIGHT",
            "DOWN", "SELECT", "PRINT", "EXECUTE", "SNAPSHOT", "INSERT", "HELP",
            "NUMPAD0", "NUMPAD1", "NUMPAD2", "NUMPAD3", "NUMPAD4", "NUMPAD5",
            "NUMPAD6", "NUMPAD7", "NUMPAD8", "NUMPAD9", "MULTIPLY", "ADD",
            "SEPARATOR", "SUBTRACT", "DECIMAL", "DIVIDE", "F1", "F2", "F3", "F4",
            "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14",
            "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
            "NUMLOCK", "SCROLL", "PAGEUP", "PAGEDOWN", "NUMPAD_SPACE",
            "NUMPAD_TAB", "NUMPAD_ENTER", "NUMPAD_F1", "NUMPAD_F2", "NUMPAD_F3",
            "NUMPAD_F4", "NUMPAD_HOME", "NUMPAD_LEFT", "NUMPAD_UP",
            "NUMPAD_RIGHT", "NUMPAD_DOWN", "NUMPAD_PRIOR", "NUMPAD_PAGEUP",
            "NUMPAD_NEXT", "NUMPAD_PAGEDOWN", "NUMPAD_END", "NUMPAD_BEGIN",
            "NUMPAD_INSERT", "NUMPAD_DELETE", "NUMPAD_EQUAL", "NUMPAD_MULTIPLY",
            "NUMPAD_ADD", "NUMPAD_SEPARATOR", "NUMPAD_SUBTRACT", "NUMPAD_DECIMAL",
            "NUMPAD_DIVIDE")
        
        for i in keys:
            self.keyMap[getattr(wx, "WXK_"+i)] = i
        for i in ("SHIFT", "ALT", "CONTROL", "MENU"):
            self.keyMap[getattr(wx, "WXK_"+i)] = ''
        
    def GetKeyPress(self, evt):
        """source: Josiah carlson - http://come.to/josiah"""
        keycode = evt.GetKeyCode()
        keyname = self.keyMap.get(keycode, None)
        modifiers = ""
        for mod, ch in ((evt.ControlDown(), 'Ctrl+'),
                        (evt.AltDown(),     'Alt+'),
                        (evt.ShiftDown(),   'Shift+'),
                        (evt.MetaDown(),    'Meta+')):
            if mod:
                modifiers += ch

        if keyname is None:
            if 27 < keycode < 256:
                keyname = chr(keycode)
            else:
                keyname = "(%s)unknown" % keycode
        return modifiers + keyname

if __name__ == "__main__":
    opts = Options()
    opts.save_use.SetValue(True)
    opts.delay.SetValue(10)
    
    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    optionsdialog = OptionsDialog(opts, None, -1, "")
    ret = optionsdialog.ShowModal()
    if ret == wx.ID_OK:
        print "OK"
    elif ret == wx.ID_CANCEL:
        print "Cancel"
    
    o = optionsdialog.GetOptions()
    print o.kb_desktop.GetValue()
    print o.kb_window.GetValue()
    print o.kb_region.GetValue()